package com.zkkj.demo.factory;

import com.zkkj.demo.service.PayChannelService;
import com.zkkj.demo.singleTon.PayChannelSingleTon;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;

import java.util.Map;

/**
 * Created by cyc
 * 2019/12/30 23:24
 * 支付方式工厂类，只需要关心接口类型和支付的渠道，通过反射机制调用
 */
public class PayChannelFactory {

    public static <T> T newInstance(Class<T> type, String payWay) {
        //从静态类中获取多种支付方式
        Map<String, String> payChannelMap = PayChannelSingleTon.getInstance().getPayChannelMap();
        String className = payChannelMap.get(payWay);
        //获取当前线程的类加载器
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        PayChannelService payChannelService = null;
        Class<?> instanceClass = null;
        try {
            instanceClass = ClassUtils.forName(className, classLoader);
            return (T) (T) ReflectionUtils.accessibleConstructor(instanceClass, new Class[0]).newInstance(new Object[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void getPayChannelByFactory(String orderId, String way){
        PayChannelService payChannelService = newInstance(PayChannelService.class,way);
        payChannelService.createOrder(orderId);
        payChannelService.payOrder(orderId);
        payChannelService.refundOrder(orderId);
    }

    public static void main(String[] args) {
        getPayChannelByFactory("123","aliPay");
    }
}
